//
//  LDXTabBar.swift
//  微博
//
//  Created by 吕东星 on 17/3/26.
//  Copyright © 2017年 lddongxing. All rights reserved.
//

import UIKit

// 设置代理方法
protocol LDXTabBarDelegate : NSObjectProtocol {
    func didComposeButtonAction()
}


class LDXTabBar: UITabBar {
    
    // 懒加载Button
    lazy var composeButton : UIButton = {
        let button  = UIButton()
        button.addTarget(self, action: #selector(composeButtonAction), for:.touchUpInside )
//        button.addTarget(self, action: #selector(composeButtonAction), for: .touchUpInside)
        //  设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
        //  设置不同状态的图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        //  根据内容设置大小
        button.sizeToFit()

        
        return button
    }()
    
    // 设置代理对象
    weak var LDXDelegate :LDXTabBarDelegate?
    
    //定义闭包属性
    var didSelectedComposeButtonAction : (()-> ())?
    
    
   // 重写自定义tabbar
    override init(frame: CGRect) {
       super.init(frame: frame)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
//        super.init(coder: aDecoder)
//        setupUI()
    }
    
    // 代理对象调用代理方法
   @objc private func composeButtonAction()  {
        // 代理方法
//       LDXDelegate?.didComposeButtonAction()
       
        //闭包
        didSelectedComposeButtonAction?()
    
    
    }
    
    // 添加视图
    func setupUI()  {
        
        self.backgroundImage = UIImage(named: "tabbar_background")
        
       addSubview(composeButton)
    }
    
    
    
    
    // 布局
    override func layoutSubviews() {
        super.layoutSubviews()
       composeButton.centerX = width * 0.5
       composeButton.centerY = height * 0.5
        let itemWidth = width/5
        var index = 0
        
        for subview in subviews {
            if subview.isKind(of: NSClassFromString("UITabBarButton")!) {
                subview.width = itemWidth
                subview.x = CGFloat (index) * itemWidth
                index+=1
                if index == 2 {
                    index += 1
                }
            }
        }
        
    }
}
